package com.xunqi.shiro.controller;

import com.xunqi.shiro.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;


@Controller
public class LoginController {

    @RequestMapping({"/", "/index"})
    public String test(Model model) {
        //model.addAttribute("name", "测试Thymeleaf");
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, HttpSession session) {

        User user = null;

        try {
            //此处不再处理登录，由shiro进行处理
            AuthenticationToken token = new UsernamePasswordToken(username,password);
            SecurityUtils.getSubject().login(token);        //调用Shiro认证
            user = (User)SecurityUtils.getSubject().getPrincipal();
            return "redirect:/index";
        } catch (Exception e) {
            session.setAttribute("msg","异常"+e.getMessage());
        }
        return "login";
    }

}
